<template>
	<!-- 	<view class="chat"> -->
	<scroll-view :style="{height: `${windowHeight-inputHeight }rpx`}" id="scrollview" scroll-y="true"
		:scroll-top='data.scrollTop' class="scroll-view" @scroll="scroll">
		<!-- 聊天主体 -->
		<view id="msgListview" class="chat-body">
			<!-- 聊天记录 -->
			<view v-for="(item,index) in data.msgList" :key="index">
				<!-- 自己发的消息 -->
				<view class="item self" v-if="item?.SenderID== 31">
					<view v-if="item.Status==null" class="loading">
						<u-loading-icon mode="circle" size="16"></u-loading-icon>
					</view>
					<!-- 发送消息，响应未发送出去 -->
					<view class="fail" v-else-if="item?.Status==false" @click="anewSend(item)"
						style="color: #f50b0b;font-size: 35rpx; font-weight: bolder;">
						！
					</view>
					<!-- //时间 -->
					<view class="time">
						<p class="chattime">{{formatTime(item?.CreatedTime * 1000)}}</p>
						<!-- 文字内容 -->
						<view class="content right">
							{{item?.Content}}
						</view>
					</view>
					<!-- 头像 -->
					<view class="touxiang">
						<up-avatar class="avatar" :src="Mymessage?.avatar" @click="goUserDetail" size='45'>
						</up-avatar>
					</view>
				</view>
				<!-- 别人发的消息 -->
				<view class="item Ai" v-if="item?.SenderID != 31">
					<!-- 头像 -->
					<view class="touxiang">
						<up-avatar class="avatar" :src="TeaMmessage?.friend_info.avatar" @click="goOther" size='45'>
						</up-avatar>
					</view>
					<!-- 文字内容 -->
					<view class="time">
						<p class="chattimeright">{{formatTime(item?.CreatedTime * 1000)}}</p>
						<view class="content left">
							{{item?.Content}}
						</view>
					</view>
				</view>
			</view>
		</view>
	</scroll-view>
	<!-- 底部消息发送栏 -->
	<!-- 用来占位，防止聊天消息被发送框遮挡 -->
	<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}" id="chat-bottom">
		<view class="send-msg" :style="{bottom:`${data.keyboardHeight - 30}rpx`}">
			<view class="uni-textarea">
				<textarea v-model="data.chatMsg" maxlength="300" confirm-type="send" placeholder="快来聊天吧~"
					:show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" auto-height class="qqq"
					:hold-keyboard='true'>
						</textarea>
			</view>
			<view class="send-btn" @touchend.prevent="handleSend">发送</view>
		</view>
	</view>
	<!-- </view> -->
</template>
<script lang="ts" setup>
	import { reactive, onUpdated, computed, getCurrentInstance, nextTick, onMounted, ref, watch } from 'vue'
	import { onLoad, onLaunch } from "@dcloudio/uni-app"
	import formatTime from '../../common/formatTime.js'
	import userStore from "../../store/modules/user.js"
	import chatRoomStore from "../../store/modules/chatroom.js"
	import { websocketSend } from "../../utils/ws.js"
	import { GetUserinfo } from '../../apis/user'
	import { Throttle } from "../../common/throttle.js"
	let beforeTen = ref()
	//聊天时间
	let chatTime = ref()
	//获取自己id
	let useUserStore = userStore()
	//未读聊天信息
	let chatData = ref([])
	//获取cahtronn信息
	let RoomMessage = chatRoomStore()
	//聊天组详情
	let TeaMmessage = ref()
	//自己的信息
	let Mymessage = ref()
	//渲染聊天记录
	let chatLog = ref([])

	let Ifsend = ref(true)
	let data = reactive({
		//键盘高度
		keyboardHeight: 0,
		//底部消息发送高度
		bottomHeight: 0,
		//滚动距离
		scrollTop: 1000,
		OldscrollTop: 0,
		//发送的消息
		chatMsg: '',
		msgList: []
	})
	onMounted(() => {

		// GetRoomMeeage()
		GetUserinfoData()
		GetTenMeeage()
	});

	onUpdated(() => {
		if (Ifsend.value == true) {
			//页面更新时调用聊天消息定位到最底部
			scrollToBottom();

		}


	})
	//export default的methods里面定义scroll方法，接收数据

	let windowHeight = computed(() => {
		return rpxTopx(uni.getSystemInfoSync().windowHeight)
	})
	// 键盘弹起来的高度+发送框高度
	let inputHeight = computed(() => {
		return data.bottomHeight + data.keyboardHeight
	})
	onLoad(() => {
		//this.data.keyboardHeight=this.rpxTopx(res.height)就行了
		//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
		uni.onKeyboardHeightChange(res => {
			data.keyboardHeight = rpxTopx(res.height)
			if (data.keyboardHeight < 0)
				data.keyboardHeight = 0;
		})
	},
	)
	// px转换成rpx
	const rpxTopx = function (px) {
		let deviceWidth = uni.getSystemInfoSync().windowWidth
		let rpx = (750 / deviceWidth) * Number(px)
		return Math.floor(rpx)
	}
	// 监视聊天发送栏高度
	const sendHeight = function () {

		setTimeout(() => {
			let query = uni.createSelectorQuery();
			query.select('.send-msg').boundingClientRect()
			query.exec(res => {
				data.bottomHeight = rpxTopx(res[0].height)
			})
		}, 10)
	}
	//滚动至聊天底部
	const scrollToBottom = function () {
		console.log("滚到底");
		const instance = getCurrentInstance();
		setTimeout(() => {
			let query = uni.createSelectorQuery().in(instance);
			query.select('#scrollview').boundingClientRect(data => {
				if (data) {
					console.log("获取到布局信息", data);
				}
			}).exec();;
			query.select('#msgListview').boundingClientRect(data => {
				if (data) {
					console.log("获取到布局信息", data);
				}
			}).exec();;
			query.exec((res) => {
				if (res[1].height > res[0].height) {
					data.scrollTop = rpxTopx(res[1].height - res[0].height)
				}
			})
		}, 15)
	}
	// const scrollToBottom = function () {
	// 	setTimeout(() => {
	// 		nextTick(() => {
	// 			data.scrollTop = 2000
	// 		})
	// 	}, 300)

	// 	console.log(data.scrollTop);
	// 	data.scrollTop = data.OldscrollTop + 100000
	// 	console.log("滚到底");
	// 	console.log(data.scrollTop);
	// 	console.log(data.OldscrollTop);
	// }
	// const scrollToBottom = function () {
	// 	console.log('ssssss');
	// 	uni.pageScrollTo({
	// 		scrollTop: 100,
	// 		selector: '#chat-bottom',
	// 		duration: 300
	// 	});
	// }
	//滚动到顶获取聊天记录（使用节流）
	function scroll(event) {
		// console.log(event);
		if (event.detail.scrollTop < 10) {
			// console.log(event.detail.scrollTop);
			// data.OldscrollTop = event.detail.scrollHeight
			Ifsend.value = false;
			Throttle(() => {
				TenMeeages()
			}, 50)
		}
	};
	// 发送消息
	const handleSend = function () {
		//如果消息不为空
		if (!data.chatMsg || !/^\s+$/.test(data.chatMsg)) {
			let obj = {
				// 生成信息的唯一标识
				//获取信息发送时间以时间戳展示
				CreatedTime: formatTime(new Date().getTime()),
				SenderID: useUserStore.user_id,
				user_id1: useUserStore.user_id,
				user_id2: TeaMmessage.value.friend_info.user_id,
				Content: data.chatMsg,
				Status: null
			}
			Ifsend.value = true
			data.msgList.push(obj);
			data.chatMsg = '';
			scrollToBottom()
			setTimeout(() => {
				console.log(111213);

			}, 500)
			//接口发送数据
			websocketSend({
				...obj
			})
			uni.getStorage({
				key: 'agentData.Status',
				success: function (res) {
					obj.Status = res.data
					data.msgList[data.msgList.length - 1] = obj
					console.log(data.msgList);

				}
			})
		}
	}
	//点击重新发送
	const anewSend = (item) => {
		console.log(item, "重新发送的消息");
		// 将聊天渲染时间进行筛选
		// chatLog.value = chatLog.value.filter(e => e.id !== item.id);
		//删除本条消息
		// 假设chatLog是一个Ref<any[]>类型的数组
		// (chatLog.value as any[]).forEach((item : any, index : number) => {
		// 	console.log(index);
		// });
		let index = data.msgList.findIndex((elem) => elem === item);
		console.log(index);
		data.msgList.splice(index, 1);
		// 将信息进行本地替换
		// saveChatRecord(item.userId1, item.userId2, item.content);
		//更改发送时间
		item.time = new Date().getTime();
		//信息接收类型初始化
		item.Status = null;
		// //将信息渲染到渲染数据列表上
		data.msgList.push({ ...item });
		// 重新发送
		websocketSend({
			...item
		})
		uni.getStorage({
			key: 'agentData.Status',
			success: function (res) {
				item.Status = res.data
				data.msgList[data.msgList.length - 1] = item
				console.log(data.msgList);

			}
		})

	}
	//时间戳转化为时间
	function timechange() {
		chatTime.value = formatTime()
	}
	//获取自己信息
	const GetUserinfoData = async () => {
		try {
			const userdata = {
				user_id: useUserStore.user_id
			}
			const res = await GetUserinfo(userdata);
			Mymessage.value = res.data

		} catch (error) {
			// 错误处理逻辑
			console.error('An error occurred while executing Captcha function:', error);
		}
	}
	//获取聊天室的信息
	async function GetRoomMeeage() {
		TeaMmessage.value = RoomMessage.chatRooms
		//获取根据聊天室ID和对方ID获取未读消息
		uni.request({
			url: 'http://193.134.210.107:8080/wx/v1/im/unreadMessages',
			method: "POST",//仅为示例，并非真实接口地址。
			data: {
				chatRoomID: TeaMmessage.value.id
			},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozMSwidXNlcl9uYW1lIjoi5YiY5ZOyNjY2IiwicGVybWlzc2lvbiI6MSwiZXhwIjoxNzIwODU4MzgyLCJpc3MiOiJiYWNrc3RhZ2UifQ.qn3DRAQ47mF7pJoibxpCX-xcOgXuVPC9IL1mmMWRQy0'
			},
			success: (res) => {
				console.log(res.data);
				if (res.data != null) {
					data.msgList = res.data
				}
				console.log(data.msgList);
			},

		})

	}
	//获取近10条的聊天记录
	async function GetTenMeeage() {
		TeaMmessage.value = RoomMessage.chatRooms
		//获取根据聊天室ID和对方ID获取未读消息
		uni.request({
			url: 'http://193.134.210.107:8080/wx/v1/im/historyMessages',
			method: "POST",//仅为示例，并非真实接口地址。
			data: {
				chatRoomID: TeaMmessage.value.id,
				earliestMessageId: TeaMmessage.value.LastMessageID
			},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozMSwidXNlcl9uYW1lIjoi5YiY5ZOyNjY2IiwicGVybWlzc2lvbiI6MSwiZXhwIjoxNzIwODU4MzgyLCJpc3MiOiJiYWNrc3RhZ2UifQ.qn3DRAQ47mF7pJoibxpCX-xcOgXuVPC9IL1mmMWRQy0'
			},
			success: (res) => {
				beforeTen.value = res.data
				data.msgList = [...beforeTen.value.data, ...data.msgList];
				console.log(data.msgList);
				data.msgList.forEach(obj => {
					obj.Status = true;
				});
				console.log(data.msgList);

			}
		})

	}
	//获取以前10条的聊天记录
	async function TenMeeages() {
		uni.showLoading({
			title: '加载中...'
		});
		console.log(data.msgList[0].ID);
		TeaMmessage.value = RoomMessage.chatRooms
		//获取根据聊天室ID和对方ID获取未读消息
		uni.request({
			url: 'http://193.134.210.107:8080/wx/v1/im/historyMessages',
			method: "POST",//仅为示例，并非真实接口地址。
			data: {
				chatRoomID: TeaMmessage.value.id,
				earliestMessageId: data.msgList[0].ID
			},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozMSwidXNlcl9uYW1lIjoi5YiY5ZOyNjY2IiwicGVybWlzc2lvbiI6MSwiZXhwIjoxNzIwODU4MzgyLCJpc3MiOiJiYWNrc3RhZ2UifQ.qn3DRAQ47mF7pJoibxpCX-xcOgXuVPC9IL1mmMWRQy0'
			},
			success: (res) => {

				// 数据从后端接口返回后，提示弹框关闭
				uni.hideLoading();
				if (res.data.data != null) {
					data.msgList = [...res.data.data, ...data.msgList];
					console.log(data.msgList);
					data.msgList.forEach(obj => {
						obj.Status = true;
					});
					console.log(data.msgList);
				} else {
					uni.showLoading({
						title: '没有更多了'
					});
					setTimeout(() => {
						uni.hideLoading();
					}, 1000)
				}

			}
		})
	}
	//点击自己跳转到自己信息
	const goUserDetail = function () {
		uni.navigateTo({
			url: `/pages/userDetail/userDetail`
		})

	}
	//点击自己跳转到用户信息
	const goOther = function () {
		uni.navigateTo({
			url: `/pages/followerDetail/followerDetail`
		})

	}
	watch(() => data.chatMsg, (newValue, oldValue) => {
		console.log(newValue);
		console.log(oldValue);
		if (newValue == '') {
			scrollToBottom()
		}
	})
</script>
<style lang="scss" scoped>
	$chatContentbgc: #FFB6C1;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	// .chat {
	.topTabbar {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		display: flex;
		margin-top: 80rpx;
		justify-content: space-between;

		.icon {
			margin-left: 20rpx;
		}

		.text {
			margin: auto;
			font-size: 16px;
			font-weight: 700;
		}

		.button {
			width: 10%;
			margin: auto 20rpx auto 0rpx;
		}
	}

	.scroll-view {
		::-webkit-scrollbar {
			display: none;
			width: 0 !important;
			height: 0 !important;
			-webkit-appearance: none;
			background: transparent;
			color: transparent;
		}

		// background-color: orange;
		background-color: #F6F6F6;

		.chat-body {
			display: flex;
			flex-direction: column;
			padding-top: 23rpx;
			// background-color:skyblue;

			.self {
				justify-content: flex-end;
			}

			.item {
				display: flex;
				padding: 23rpx 30rpx;

				.loading {
					margin-top: 55upx;
				}

				.fail {
					margin-top: 55upx;
				}

				.touxiang {
					margin-top: 20upx;
				}

				// background-color: greenyellow;
				.chattime {
					font-size: 22upx;
					margin-bottom: 4upx;
				}

				.chattimeright {
					font-size: 22upx;
					margin-bottom: 4upx;

				}

				.right {
					background-color: $chatContentbgc;
				}

				.left {
					background-color: #FFFFFF;
				}

				// 聊天消息的三角形
				.right::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					left: 100%;
					top: 10px;
					border: 12rpx solid transparent;
					border-left: 12rpx solid $chatContentbgc;
				}

				.left::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					top: 10px;
					right: 100%;
					border: 12rpx solid transparent;
					border-right: 12rpx solid #FFFFFF;
				}

				.content {
					position: relative;
					max-width: 486rpx;
					border-radius: 8rpx;
					word-wrap: break-word;
					padding: 24rpx 24rpx;
					margin: 0 24rpx;
					border-radius: 5px;
					font-size: 32rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
					// line-height: 42rpx;
				}

				// .avatar {
				// 	// display: flex;
				// 	// justify-content: center;
				// 	// width: 78rpx;
				// 	// height: 78rpx;

				// 	background: $sendBtnbgc;
				// 	// border-radius: 50rpx;
				// 	// overflow: hidden;

				// 	image {
				// 		align-self: center;
				// 	}

				// }
			}
		}
	}

	/* 底部聊天发送栏 */
	.chat-bottom {
		width: 100%;
		height: 100rpx;
		background: #F4F5F7;
		transition: all 0.1s ease;

		.send-msg {
			display: flex;
			align-items: flex-end;
			padding: 16rpx 30rpx;
			width: 100%;
			min-height: 137rpx;
			position: fixed;
			bottom: 0;
			background: #fff;
			transition: all 0.1s ease;
		}

		.uni-textarea {
			padding-bottom: 50rpx;

			textarea {
				width: 537rpx;
				min-height: 75rpx;
				max-height: 500rpx;
				background: #f1f1f1;
				border-radius: 40rpx;
				font-size: 32rpx;
				font-family: PingFang SC;
				color: #333333;
				line-height: 74rpx;
				padding: 5rpx 8rpx;
				text-indent: 30rpx;
			}
		}

		.send-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 53rpx;
			margin-left: 25rpx;
			width: 120rpx;
			height: 75rpx;
			background: #ed5a65;
			border-radius: 50rpx;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			line-height: 28rpx;
		}
	}

	// }
</style>